//
//  WHFileManagerHelper.m
//  LvZhongMagicKey
//
//  Created by 邓伟浩 on 2018/1/4.
//  Copyright © 2018年 邓伟浩. All rights reserved.
//

#import "WHFileManagerHelper.h"
#import "SDWebImageManager.h"

@implementation WHFileManagerHelper

+ (NSString *)docPath {
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+ (NSString *)cachePath {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    return cachePath;
}

/** 缓存目录文件大小 */
+ (float)readCacheSize {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [self folderSizeAtPath:cachePath];
}

/** 计算文件夹大小 */
+ (float)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSArray *subPathArray = [manager subpathsAtPath:folderPath];
    NSEnumerator *childFilesEnumerator = [subPathArray objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        //获取文件全路径
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
//        DLog(@"fileName: %@", fileName);
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    return folderSize/(1000.0 * 1000.0);
    
}

/** 计算单文件大小 */
+ (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        NSDictionary *fileAttributes = [manager attributesOfItemAtPath:filePath error:nil];
        long long fileSize = [fileAttributes fileSize];
//        DLog(@"fileSize: %lld", fileSize);
        return fileSize;
    }
    return 0;
}

/** 清除缓存 */
+ (void)clearFile {    
    [[SDImageCache sharedImageCache] clearDisk];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *fileName in files) {
        
        NSError *error = nil ;
        //获取文件全路径
        NSString *fileAbsolutePath = [cachePath stringByAppendingPathComponent:fileName];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileAbsolutePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:fileAbsolutePath error:&error];
        }
    }
    
}

@end
